<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas id="myCanvas">

    </canvas>
    <script>
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        //矩形
        ctx.beginPath();
        ctx.fillStyle = "#FF0000";
        let x = 0;
        let y = 0;
        const speed = 3;
        x += 1;
        ctx.fillRect(x, y, 50, 50);
        //上下左右移动
        document.onkeydown = function (event) {
            console.log(event.keyCode);
            switch (event.keyCode) {
                //上
                case 38:
                    y -= speed;
                    break;
                //下
                case 40:
                    y += speed;
                    break;
                //左
                case 37:
                    x -= speed;
                    break;
                //右
                case 39:
                    x += speed;
                    break;
                default:
                    break;
            }
            ctx.clearRect(0, 0, c.width, c.height);
            ctx.fillRect(x, y, 50, 50);

        };

    </script>
</body>

</html>